package com.itheima.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.itheima.common.PageInfo;
import com.itheima.common.ThreadLocalIUtil;
import com.itheima.dto.RecordsDto;
import com.itheima.dto.SetmealDishesDto;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Category;
import com.itheima.pojo.Records;
import com.itheima.pojo.SetmealDishes;
import com.itheima.service.SetmealService;
import com.itheima.vo.RecordsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private CategoryMapper categoryMapper;


    @Override
    public PageInfo<RecordsVo> page(String name, Integer page, Integer pageSize,Integer type) {

        PageInfo<RecordsVo> pageInfo = new PageInfo<>();

        List<RecordsVo> newlist=new ArrayList<>();

        Integer start = (page - 1) * pageSize;
        List<Records> list = setmealMapper.page(name, start, pageSize,type);
        for (Records records : list) {
            RecordsVo recordsVo=new RecordsVo();
            BeanUtils.copyProperties(records, recordsVo);

            String categoryId = records.getCategoryId();
            Category categorybyId = categoryMapper.getById(categoryId);
            recordsVo.setCategoryName(categorybyId.getName());
            newlist.add(recordsVo);
        }

        pageInfo.setRecords(newlist);
        pageInfo.setSize(pageSize);
        pageInfo.setCurrent(page);
        long count = setmealMapper.count();
        pageInfo.setTotal(count);

        return pageInfo;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean save(RecordsDto recordsDto) {

        // 获取category表上的id
        String categoryId = recordsDto.getCategoryId();
        // 判断id是否存在
        Category category = categoryMapper.getById(categoryId);
        if (category == null) {
            return false;
        }


        Records records = new Records();
        String id = IdUtil.getSnowflakeNextIdStr();
        recordsDto.setId(id);
        BeanUtils.copyProperties(recordsDto, records);
        records.setCreateUser(ThreadLocalIUtil.getId());
        records.setCategoryId(categoryId);
        int save = setmealMapper.save(records);
        // 套餐信息 套餐内容
        // 1获取当前套餐内容
        List<SetmealDishesDto> setmealDishesDtos = recordsDto.getSetmealDishes();
        // 创建一个List容器用来返回
        List<SetmealDishes> newsetmealDishes = new ArrayList<>();
        // 新建一个套餐内容容器
        SetmealDishes setmealDishes = new SetmealDishes();
        // 2遍历到集合数据库中
        if (!CollectionUtil.isEmpty(setmealDishesDtos)) {
            for (SetmealDishesDto item : setmealDishesDtos) {
                if (item == null) {
                    continue;
                }
                BeanUtils.copyProperties(item, setmealDishes);
                setmealDishes.setSetmealId(recordsDto.getId());
                String setmealdishesId = IdUtil.getSnowflakeNextIdStr();
                setmealDishes.setId(setmealdishesId);
                newsetmealDishes.add(setmealDishes);

            }
        }
        // 3批量插入套餐内容信息
        int rs = setmealMapper.batchInsertSetmealDishes(newsetmealDishes);
        if (rs != newsetmealDishes.size()) {
            throw new RuntimeException("套餐内容添加失败");
        }
        return (save > 0);
    }

    @Override
    public boolean delete(List<String> ids) {

        List<Records> byIds = getByIds(ids);
        for (Records records : byIds) {
            if (records.getStatus()==1){
                return false;
            }
        }
        int delete = setmealMapper.delete(ids);

        return delete > 0;
    }

    @Override
    public boolean sell(List<String> ids, int status) {
        int sell = setmealMapper.sell(ids, status);
        return sell > 0;

    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean update(RecordsDto recordsDto) {
        if (recordsDto == null) {
            throw new RuntimeException("参数不能为空");
        }
        RecordsVo recordsVo = new RecordsVo();
        BeanUtils.copyProperties(recordsDto, recordsVo);
        LocalDateTime ldt = LocalDateTime.now();
        recordsVo.setUpdateTime(ldt);
        recordsVo.setCreateUser(ThreadLocalIUtil.getId());
        int update = setmealMapper.update(recordsDto);
        if (update == 0) {
            return false;
        }
        // 更新套餐内容
        int total = setmealMapper.countsetmealdishesById(recordsDto.getId());
        if (total > 0) {
            int reId = setmealMapper.removesetmealdishesById(recordsDto.getId());
            if (reId == 0) {
                throw new RuntimeException("删除失败");
            }
        }
        List<SetmealDishesDto> setmealDishess = recordsDto.getSetmealDishes();
        List<SetmealDishes> newSetmealDishes = new ArrayList<>();
        if (!CollectionUtil.isEmpty(setmealDishess)) {
            for (SetmealDishesDto item : setmealDishess) {
                if (item == null) {
                    continue;
                }
                SetmealDishes setmealDishes = new SetmealDishes();
                BeanUtils.copyProperties(item, setmealDishes);
                setmealDishes.setSetmealId(recordsDto.getId());
                String setmealdishesId = IdUtil.getSnowflakeNextIdStr();
                setmealDishes.setId(setmealdishesId);
                newSetmealDishes.add(setmealDishes);

            }
        }
        // 批量插入套餐内容信息
        int rs = setmealMapper.batchInsertSetmealDishes(newSetmealDishes);
        if (rs != newSetmealDishes.size()) {
            throw new RuntimeException("套餐添加失败");
        }






        return update > 0 && rs > 0;
    }



    @Override
    public RecordsVo getById(String id) {
        Records records = setmealMapper.getById(id);
        if (records == null) {
            return null;
        }
        //创建新的SetmealDishesVo容器把旧的SetmealDishes添加进去，并在SetmealDishesVo中添加Flavor 口味


        RecordsVo recordsVo=new RecordsVo();
        BeanUtils.copyProperties(records,recordsVo);

        List<SetmealDishes> mealDishesById = getMealDishesById(id);
        // List<SetmealDishesVo> setMealDishesVos=new ArrayList<>();
        // for (SetmealDishes setmealDishes : mealDishesById) {
        //     SetmealDishesVo setmealDishesVo=new SetmealDishesVo();
        //     BeanUtils.copyProperties(setmealDishes,setmealDishesVo);
        //
        // }
        recordsVo.setSetmealDishes(mealDishesById);


        return recordsVo;
    }

    /**
     * 按一群id查找records的list
     * @param ids
     * @return
     */
    public List<Records> getByIds(List<String> ids) {
        List<Records> byIds = setmealMapper.getByIds(ids);
        return byIds;
    }

    /**
     * 根据id找到MealDishes
     * @param id
     * @return
     */
    @Override
    public List<SetmealDishes> getMealDishesById(String id) {
        List<SetmealDishes> setMealDishes = setmealMapper.getmealDishesById(id);

        return setMealDishes;
    }
    @Override
    public RecordsVo clientGetList(String setmealId) {
        Records records = setmealMapper.getById(setmealId);
        RecordsVo recordsVo=new RecordsVo();
        BeanUtils.copyProperties(records,recordsVo);

        List<SetmealDishes> mealDishesById = getMealDishesById(setmealId);
        recordsVo.setSetmealDishes(mealDishesById);
        return   recordsVo;
    }

    @Override
    public List<Records> clientgetList(String categoryId, String status) {
        List<Records> records = setmealMapper.clientgetList(categoryId, status);
        return  records;

    }
}
